import { createSlice } from "@reduxjs/toolkit";

const countSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0
  },
  reducers: {
    plus: (state, action)=>{
      console.log(state.count, action);
    // reducer借助toolkit中的immer实现对state直接修改
      state.count+=action.payload.value
    },
    minus: (state, action)=>{
      state.count-=action.payload.value
    },
    // reducer借助toolkit中实现异步处理,但依然不能直接在reducer里面写异步逻辑
    asyncPlus: (state, action)=>{
      state.count+=action.payload.value
    },
  }
})

export const {plus:pAction, minus:mAction, asyncPlus}=countSlice.actions

// The function below is called a thunk and allows us to perform async logic.
// It can be dispatched like a regular action: `dispatch(incrementAsync(10))`.
// This will call the thunk with the `dispatch` function as the first argument.
// Async code can then be executed and other actions can be dispatched
export const apAction = (value) => dispatch => {
  setTimeout(() => {
    dispatch(asyncPlus(value))
  }, 1000)
}

export default countSlice.reducer